import os
import time
from random import random

from django.core.files import File
from django.shortcuts import get_object_or_404

from User.models import SiteUser
from .models import FileModel, FileMeta, BlockFileModel


def save_file(user, data):
    file_path = data.get('temp_file_path')
    md5 = data.get('file_md5')
    full_filename = data.get("full_filename")
    policy_block = data.get("block", False)

    destination = data.get('descript')
    file_meta = None
    if destination:
        file_meta = FileMeta.objects.create(
            file_description=destination,
            user=SiteUser.objects.get(id=user)
        )

    file_instance = None

    # 打开临时文件进行操作
    with open(file_path, 'rb') as file:
        file = File(file)
        file.name = f"{time.time()}-{random()}-{full_filename}"

        file_instance = FileModel(
            filename=full_filename,
            file=file,
            md5=md5,
            block_order=data.get('block_order', 0),
        )  # 这里是上传文件

        file_instance.save()  # 保存文件

        if not policy_block:  # 如果不是分区上传
            block_file_model = BlockFileModel.objects.create(
                files=f"{file_instance.id}",
                show_filename=data.get('filename'),
            )  # 单个文件可以直接记录整个分区
        if file_meta is not None:
            block_file_model.file_meta = file_meta

    # 删除临时文件
    os.remove(file_path)

    print(f"文件: {full_filename}保存成功")
    return {
        "id": file_instance.id,
        "order": file_instance.block_order
    }
